package com.example.taluo.controller;

import com.example.taluo.entity.dto.LoginRequest;
import com.example.taluo.entity.dto.AuthResponse;
import com.example.taluo.entity.dto.ResponseDO;
import com.example.taluo.entity.User;
import com.example.taluo.security.TokenProvider;
import com.example.taluo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Autowired
    private TokenProvider tokenProvider;
    
    @Autowired
    private UserService userService; // 需要实现用户验证服务

    @PostMapping("/login")
    public ResponseDO login(@RequestBody LoginRequest loginRequest) {
        // 1. 验证用户名密码
        User user = userService.authenticate(loginRequest.getUsername(), loginRequest.getPassword());

        if (user == null) {
            return ResponseDO.fail("用户名或密码错误");
        }
        // 2. 生成Token
        String token = tokenProvider.generateToken(String.valueOf(user.getId()));

        // 3. 返回Token
        return ResponseDO.success(new AuthResponse(token));
    }
}
